package com.situ.music.activity;

import android.Manifest;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ListView;


import com.situ.music.R;
import com.situ.music.adapter.FileAdapter;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private  String[] requestPermissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    
    // 代表当前正在浏览的目录，初始是sdcard的根目录
    private File currentDirectoryFile;
    private ListView listView;
    private FileAdapter fileAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);

        // 首先获得sdcard的根目录
        currentDirectoryFile = getSDPath();
        // 列出这个文件夹下面所有文件和文件夹
        File[] files = currentDirectoryFile.listFiles();
        for (File file : files) {
            Log.d(TAG, file.getAbsolutePath());
        }
        fileAdapter = new FileAdapter(this);
        fileAdapter.setData(currentDirectoryFile);
        listView.setAdapter(fileAdapter);

    }

    private File getSDPath() {
        File sdCard = null;
        boolean isSDCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (isSDCardExist) {
            sdCard = Environment.getExternalStorageDirectory();
        } else {
            sdCard = Environment.getRootDirectory();
        }
        return sdCard;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            // Environment.getExternalStorageDirectory() 得到sd卡的根目录
            if (!currentDirectoryFile.equals(Environment.getExternalStorageDirectory())) {
                String parentPath = currentDirectoryFile.getParent();
                // 按了back键将上一层目录更新成最新的目录
                currentDirectoryFile = new File(parentPath);
                fileAdapter.setData(currentDirectoryFile);
            } else {
                // 已经是sd卡根目录
                finish();
            }
            // 代表我自己处理了back按键
            return  true;
        }

        return super.onKeyDown(keyCode, event);
    }

    public void updateCurrentPath(File file) {
        currentDirectoryFile = file;
    }
}